package com.herench.bridge.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.herench.bridge.ReaderService;
import com.herench.bridge.StrangeMessage;
import com.herench.bridge.utils.DesUtil;
import com.herench.bridge.utils.HttpClientSupport;
import org.apache.log4j.Logger;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * 对账服务
 * Created by ThinkPad on 2017/6/4.
 */

@Component("readerService")
@javax.jws.WebService(endpointInterface = "com.herench.bridge.ReaderService", serviceName = "readerService", targetNamespace = "http://bridge.herench.com/")
public class ReaderServiceImpl implements ReaderService {

    private static final Logger logger = Logger.getLogger(ReaderServiceImpl.class);

    @Value("${payUrl}")
    private String payUrl;

    @Override
    public String validate(String message) {
//        return new MessageProvider().validate(msg,payUrl);
        logger.info("request:" + message);
        StrangeMessage responseMessage = new StrangeMessage();

        try {
            StrangeMessage requestMessage = new StrangeMessage(message);

            String dateStr = requestMessage.getAttrFromCommitDataRow("RECONCILIATION_DATE");
            Assert.hasLength(dateStr, "账目日期参数不能为空");
            String sysCode = requestMessage.getAttrFromClientInfo("OPT_ID");
            Assert.hasLength(sysCode, "OPT_ID 为空");
            String method = requestMessage.getAttrFromClientInfo("METHOD");
            Assert.hasLength(method, "METHOD 为空");
            String moneyType = requestMessage.getAttrFromCommitDataRow("MONEY_TYPE");
            Assert.hasLength(moneyType, "MONEY_TYPE 为空");


            String channelCode = null;
            if (sysCode.equals("100101")) {
                if (moneyType.equals("20")) {
                    channelCode = "100001";
                } else if (moneyType.equals("21")) {
                    channelCode = "100002";
                } else if (moneyType.equals("22")) {

                }

            } else if (sysCode.equals("100102")) {
                channelCode = "100003";
            } else if (sysCode.equals("100106")) {
                if (moneyType.equals("20")) {
                    channelCode = "100010";
                } else if (moneyType.equals("21")) {
                    channelCode = "100009";
                } else if (moneyType.equals("22")) {

                }

            } else if (sysCode.equals("100107")) {
                if (moneyType.equals("20")) {
                    channelCode = "100012";
                } else if (moneyType.equals("21")) {
                    channelCode = "100011";
                } else if (moneyType.equals("22")) {

                }

            }
            Assert.hasLength(channelCode, "支付渠道未配置或者未开放");
            Map<String, Object> params = new HashMap<>();
            params.put("billDate", dateStr);
            params.put("channelCode", channelCode);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("funcode", "790001");
            jsonObject.put("args", DesUtil.encrypt(JSON.toJSONString(params)));
            String str = HttpClientSupport.doPost(payUrl, jsonObject.toString(), "UTF-8");
            JSONObject resJson = JSON.parseObject(str);
            if (resJson.getString("code").equals("0")) {
                JSONObject data = resJson.getJSONObject("data");
                String state = data.getString("state");
                String stateDesc = data.getString("stateDesc");
                JSONObject bills = data.getJSONObject("bills");
                if (state.equals("0")) {
                    if (method.equals("total")) {
                        Element element = DocumentHelper.createElement("DataRow");
                        element.addAttribute("TRANSACTION_COUNT", (Integer.valueOf(bills.getString("transCount")) + Integer.valueOf(bills.getString("refundCount"))) + "");
                        element.addAttribute("TRANSACTION_AMOUNT", bills.getString("actualAmount"));
                        responseMessage.addReturnDataRow(element);
                    } else if (method.equals("detail")) {
                        JSONArray array = bills.getJSONArray("billDetails");
                        if (array != null && array.size() > 0) {
                            for (int i = 0; i < array.size(); i++) {
                                JSONObject temp = array.getJSONObject(i);
                                Element element = DocumentHelper.createElement("DataRow");
                                element.addAttribute("TERMINAL_NUMBER", temp.getString("channelCode"));
                                element.addAttribute("POS_NO", temp.getString("terminalId"));
                                element.addAttribute("TRAN_AMT", temp.getString("receiptAmount"));
                                element.addAttribute("TRAN_TYPE", temp.getString("tradeType"));
                                element.addAttribute("TRAN_DATE", temp.getString("startTime"));
                                element.addAttribute("CARD_ID", temp.getString("buyerId"));
                                String outRequestNo = temp.getString("outRequestNo");
                                if (StringUtils.hasLength(outRequestNo) && !outRequestNo.equals("0")) {
                                    element.addAttribute("TRANS_NO", outRequestNo);
                                } else {
                                    element.addAttribute("TRANS_NO", temp.getString("outTransNo"));
                                }
                                responseMessage.addReturnDataRow(element);
                            }
                        }
                    }
                }
                responseMessage.addExecuteStatus(state);
                responseMessage.addExecuteMessage(stateDesc);
            } else {
                responseMessage.addExecuteStatus(resJson.getString("code"));
                responseMessage.addExecuteMessage(resJson.getString("message"));
            }
        } catch (Exception e) {
            responseMessage.addExecuteStatus("1");
            if (e.getMessage() == null) {
                responseMessage.addExecuteMessage("请求超时，请重试！");
            } else {
                responseMessage.addExecuteMessage(e.getMessage());
            }
            logger.info("异常信息:" + e.getCause());
            e.printStackTrace();
        }
        logger.info("response:" + responseMessage);
        return responseMessage.getBody().asXML();
    }
}
